import sys
import bluetooth
from ble_advertising import advertising_payload

# 定义 BLE 事件
_IRQ_CENTRAL_CONNECT = 1
_IRQ_CENTRAL_DISCONNECT = 2
_IRQ_GATTS_WRITE = 3
_IRQ_GATTC_NOTIFY = 4

# 定义标志
_FLAG_READ = 0x0002
_FLAG_WRITE = 0x0008
_FLAG_NOTIFY = 0x0010

# 定义多个服务和特征的 UUID
# 服务 1
_SERVICE_UUID_1 = bluetooth.UUID("4fafc201-1fb5-459e-8fcc-c5c9c331914b")
_CHAR_UUID_1_1 = bluetooth.UUID("beb5483e-36e1-4688-b7f5-ea07361b26a8")
_CHAR_UUID_1_2 = bluetooth.UUID("beb5483e-36e1-4688-b7f5-ea07361b26a9")

# 服务 2
_SERVICE_UUID_2 = bluetooth.UUID("5fafc201-1fb5-459e-8fcc-c5c9c331914c")
_CHAR_UUID_2_1 = bluetooth.UUID("feb5483e-36e1-4688-b7f5-ea07361b26aa")

_CHAR_UUID_2_2 = bluetooth.UUID("feb5483e-36e1-4688-b7f5-ea07361b26ab")

# 定义特征
_CHAR_1_1 = (
    _CHAR_UUID_1_1,
    _FLAG_READ | _FLAG_WRITE,
)
_CHAR_1_2 = (
    _CHAR_UUID_1_2,
    _FLAG_NOTIFY,
)
_CHAR_2_1 = (
    _CHAR_UUID_2_1,
    _FLAG_READ,
)
_CHAR_2_2 = (
    _CHAR_UUID_2_2,
    _FLAG_WRITE,
)

# 定义服务
_SERVICE_1 = (
    _SERVICE_UUID_1,
    (_CHAR_1_1, _CHAR_1_2),
)
# _SERVICE_2 = (
#     _SERVICE_UUID_2,
#     (_CHAR_2_1, _CHAR_2_2),
# )

# 定义所有服务
# _SERVICES = (_SERVICE_1, _SERVICE_2)
_SERVICES = (_SERVICE_1,)


class BLEHandler:
    def __init__(self, ble, name="mpy"):
        self._ble = ble
        self._ble.active(True)
        self._ble.irq(self._irq)
        # 注册所有服务和特征
        self._handles = self._ble.gatts_register_services(_SERVICES)
        self._connections = set()
        self._payload = advertising_payload(name=name, services=[_SERVICE_UUID_1, _SERVICE_UUID_2])
        self._advertise()

    def _irq(self, event, data):
        if event == _IRQ_CENTRAL_CONNECT:
            conn_handle, _, _ = data
            self._connections.add(conn_handle)
            print("Connected")
        elif event == _IRQ_CENTRAL_DISCONNECT:
            conn_handle, _, _ = data
            self._connections.remove(conn_handle)
            print("Disconnected")
            self._advertise()
        elif event == _IRQ_GATTS_WRITE:
            conn_handle, value_handle = data
            # 处理写入事件
            for service_handles, service in zip(self._handles, _SERVICES):
                for char_handle, char in zip(service_handles, service[1]):
                    if char_handle == value_handle:
                        print(f"Received write on {char[0]}")
                        data = self._ble.gatts_read(value_handle)
                        print(f"Data: {data}")
                        print("Received data:", data)
                        mac_str = binascii.hexlify(data).decode()
                        print(mac_str)
                        
    def _advertise(self, interval_us=500000):
        self._ble.gap_advertise(interval_us, adv_data=self._payload)
        
    def utf8_string_to_hex_uint8array(self, text):
        """
        Converts a UTF-8 string to a hex-encoded Uint8Array.

        Args:
            text: The UTF-8 string to convert.

        Returns:
            A string representing the hex-encoded Uint8Array.
        """
        utf8_bytes = text.encode('utf-8')
        hex_string = ''.join([f'{byte:02x}' for byte in utf8_bytes])
        return hex_string

    def send_large_data(self, large_data):
        chunk_size = 20  # BLE 数据包最大长度通常为 20 字节
        for i in range(0, len(large_data), chunk_size):
            chunk = large_data[i:i + chunk_size]
            for conn_handle in self._connections:
                self._ble.gatts_notify(conn_handle, self._handle, chunk)

# 初始化 BLE
ble = bluetooth.BLE()
ble_handler = BLEHandler(ble)



#######################################################################################

# # Example usage
# text_string = "H 王博士"
# hex_uint8array = utf8_string_to_hex_uint8array(text_string)
# print(hex_uint8array)
# 
# byte_array = bytes.fromhex(hex_uint8array)
# 
# string_china = byte_array.decode('utf-8', 'ignore')
# 
# print(string_china)
